package com.elong.businesstravel.modules.init;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;

import com.android.support.jhf.debug.DebugLog;
//import com.alipay.android.app.sdk.AliPay;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.android.support.jhf.utils.FileUtils;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.Constant;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.entitys.AlipayResult;
import com.elong.businesstravel.include.Version;
import com.elong.businesstravel.modules.home.HomeActivity;
import com.elong.businesstravel.modules.home.NewHomeActivity;
import com.elong.businesstravel.protocol.city.GetCityRequest;
import com.elong.businesstravel.protocol.city.GetCityResponse;
import com.elong.businesstravel.protocol.city.GetPoiByCityRequest;
import com.elong.businesstravel.protocol.city.GetPoiByCityResponse;
import com.elong.businesstravel.protocol.ticket.GetStationListRequest;
import com.elong.businesstravel.protocol.ticket.GetStationListResponse;
import com.elong.businesstravel.protocol.version.GetVersionRequest;
import com.elong.businesstravel.protocol.version.GetVersionResponse;

/**
 * 初始化界面
 * 
 * @author lenovo
 * 
 */
public class InitActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);
//		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_init);

		ExecutorService executorService = Executors.newSingleThreadExecutor();
		executorService.execute(new Runnable() {

			@Override
			public void run() {

				// 加载城市缓存
				try {
					getCityListCache();
					getStationListCache();
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (null == mApplication.mCity && null == mApplication.mTrainStations) {
					// 没有缓存延时
					try {
						TimeUnit.SECONDS.sleep(2);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				

				HandlerPostUI.getHandlerPostUI(new Runnable() {

					@Override
					public void run() {
						goActivity();
					}
				});
			}
		});
		// callAppPayment(null);
	}

	/**
	 * 跳转页面
	 */
	private void goActivity() {
		int currentVersionCode = 1;
		int lastVersionCode = 0;
		try {
			currentVersionCode = Integer.parseInt(Version.versionCode);
			lastVersionCode = Integer.parseInt(SaveUserOperate
					.getLastVersionCode(mContext));
		} catch (Exception e) {
		}

		if (currentVersionCode > lastVersionCode) {
			// 引导页
			Intent intent = new Intent(mContext, GuideActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
		} else {
			// 跳转到首页
//			Intent intent = new Intent(mContext, HomeActivity.class);
			Intent intent = new Intent(mContext,
					NewHomeActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(android.R.anim.fade_in,
					android.R.anim.fade_out);
		}
	}

	/**
	 * 调用支付宝客户端
	 */
	// private void callAppPayment(AlipayResult alipayResult) {
	// // String redrecturl = alipayResult.redrecturl;
	// // final String paramString = requestParamEncode(redrecturl);
	// final String paramString =
	// "partner=\"2088001966153085\"&seller=\"2088001966153085\"&out_trade_no=\"6880997\"&subject=\"chailvtong\"&body=\"chailvtong\"&total_fee=\"0.01\"&notify_url=\"http://agent.gaia.elong.com/Payment.ExternalInterface/AlipaySecurityPayReceived.aspx\"&sign=\"sAdX%2b%2fYImO1l7KJabHgIxTW5qLM4Lerf8XOLwu7dlcSxK3QTppR8IF%2bMObpSMJShXYaPeKvjnk2bs2%2bJW6emlfhw1KqM1VjOlnz7xy7UolIQ4PUKfFMPVMGLmhJMqtbtGSRWzHt4fX8wj4SRGpK%2fVHNIMHYYghU7GuowAasu8iA%3d\"&sign_type=\"RSA\"";
	// // 获取订单组装字符串
	// new Thread() {
	// public void run() {
	// // PayHelper payHelper = new PayHelper((Activity)mContext);
	// // String result = payHelper.pay4Client(paramString);
	// // String result = payHelper.pay4Msp(paramString);
	// // 获取Alipay对象，构造参数为当前Activity和Handler实例对象
	// AliPay alipay = new AliPay((Activity) mContext, mHandler);
	// // 调用pay方法，将订单信息传入
	// String result = alipay.pay(paramString);
	// // 处理返回结果
	// }
	// }.start();
	//
	// }
	private Handler mHandler = new Handler();

	private void getVersion() {
		NetworkClient.getNetworkClient().PostRequest(
				new GetVersionRequest(mContext), new GetVersionResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
					}
				});
	}

	private void getAllCityPoi() {
		// NetworkClient.getNetworkClient().PostRequest(new
		// GetAllCityPoiRequest(mContext), new GetAllCityPoiResponse(){
		// @Override
		// public void onResponse(
		// ResponseHandlerInterface responseHandlerInterface) {
		// }
		// });

		// 所有城市POI
		// GetAllCityPoiRequest getAllCityPoiRequest = new
		// GetAllCityPoiRequest(mContext);
		// GetAllCityPoiResponse getAllCityPoiResponse = new
		// GetAllCityPoiResponse(mContext);
		// getAllCityPoiResponse.onSuccess(0, new Header[]{}, "", null);
		// String allCityPoiString = null;
		// ByteArrayOutputStream byteArrayOutputStream = null;
		// InputStream allCityPoiInputStream = null;
		// try {
		// byteArrayOutputStream = new ByteArrayOutputStream();
		// allCityPoiInputStream = getAssets().open("file/AllCityPoi.json");
		// byte[] b = new byte[4096];
		// int len = -1;
		// while (-1 != (len = allCityPoiInputStream.read(b))) {
		// byteArrayOutputStream.write(b, 0, len);
		// }
		// byteArrayOutputStream.flush();
		// allCityPoiString = byteArrayOutputStream.toString();
		// getAllCityPoiResponse.onSuccess(200, null, allCityPoiString, null);
		// } catch (IOException e) {
		// e.printStackTrace();
		// } finally {
		// try {
		// byteArrayOutputStream.close();
		// allCityPoiInputStream.close();
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		// }

		// long start = System.currentTimeMillis();
		// String string = FileUtils.readFile(new File(Environment
		// .getExternalStorageDirectory() + "/" + "response.txt"));
		// try {
		//
		// long end = System.currentTimeMillis();
		//
		//
		// JSONObject jsonObject = new JSONObject(string);
		//
		// end = System.currentTimeMillis();
		//
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }
	}

	/**
	 * 获取城市列表缓存
	 * 
	 * @param context
	 */
	private void getCityListCache() {
		final Md5FileNameGenerator md5FileNameGenerator = new Md5FileNameGenerator();
		final GetCityRequest getCityRequest = new GetCityRequest(mContext);
		final GetCityResponse getCityResponse = new GetCityResponse();
		final String cacheKeyString = getCacheDir() + "/"
				+ md5FileNameGenerator.generate(getCityRequest.getCacheKey());
		File file = new File(cacheKeyString);
		if (file.exists()) {
			String cityString = FileUtils.readFile(file);
			getCityResponse.onSuccess(200, null, cityString, null);
			mApplication.mCity = getCityResponse.mCity;
		}

	}
	
	/**
	 * 获取车站列表缓存
	 * 
	 * @param context
	 */
	private void getStationListCache() {
		final Md5FileNameGenerator md5FileNameGenerator = new Md5FileNameGenerator();
		final GetStationListRequest getStationListRequest = new GetStationListRequest(mContext);
		final GetStationListResponse getStationListResponse = new GetStationListResponse();
		final String cacheKeyString = getCacheDir() + "/"
				+ md5FileNameGenerator.generate(getStationListRequest.getCacheKey());
		File file = new File(cacheKeyString);
		if (file.exists()) {
			String cityString = FileUtils.readFile(file);
			getStationListResponse.onSuccess(200, null, cityString, null);
			mApplication.mTrainStations = getStationListResponse.trainStations;
		}

	}

}
